<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use App\Models\Log as LogModel;
use Zhuzhichao\IpLocationZh\Ip;

class LogMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $request->attributes->set('startTime', microtime(true));


        return $next($request);
    }

    public function terminate($request)
    {

        try {
            $startTime = $request->attributes->get('startTime', null);
            $executionTime = $startTime ? (int)((microtime(true) - $startTime) * 1000) : 0;

            $userAgent = $request->header('User-Agent') ?? '未知';
            $osInfo = $this->getOS($userAgent);
            $browserInfo = $this->getBrowser($userAgent);

            $ip = $request->ip();
            $location = Ip::find($ip);

            $infoData = [
                'browser' =>  "{$browserInfo['name']} {$browserInfo['version']}",
                'operator' => Auth::user()->nickname ?? '游客',
                'ip' => $ip,
                'region' => $location[4] ? "{$location[0]}{$location[1]}{$location[2]}" : $location[0],
                'os' => "{$osInfo['name']} {$osInfo['version']}",
                'requestUri' => $request->getRequestUri(),
                'method' => $request->method(),
                'executionTime' => $executionTime,
            ];

            LogModel::create($infoData);

        } catch (\Throwable $e) {
            Log::error('日志记录失败: ' . $e->getMessage());
        }
    }

    protected function getOS($userAgent)
    {
        $osArray = [
            'Windows 11' => '/Windows NT 10.0; Win64; x64;.*?Windows 11/',
            'Windows 10 / Server 2016+' => '/Windows NT 10.0/',
            'Windows 8.1 / Server 2012 R2' => '/Windows NT 6.3/',
            'Windows 8 / Server 2012' => '/Windows NT 6.2/',
            'Windows 7 / Server 2008 R2' => '/Windows NT 6.1/',
            'Mac OS' => '/Macintosh;.*Mac OS X ([\d_]+)/',
            'iOS' => '/iPhone|iPad;.*OS ([\d_]+)/',
            'Android' => '/Android ([\d\.]+)/',
            'Linux' => '/Linux/',
        ];

        foreach ($osArray as $name => $pattern) {
            if (preg_match($pattern, $userAgent, $matches)) {
                $version = $matches[1] ?? '';
                $version = str_replace('_', '.', $version);
                return ['name' => $name, 'version' => $version];
            }
        }

        return ['name' => '未知', 'version' => ''];
    }

    protected function getBrowser(string $userAgent)
    {
        $browsers = [
            'Edge' => '/Edg\/([\d\.]+)/',
            'Opera' => '/OPR\/([\d\.]+)/',
            'Chrome' => '/Chrome\/([\d\.]+)/',
            'Firefox' => '/Firefox\/([\d\.]+)/',
            'Safari' => '/Version\/([\d\.]+).*Safari/',
            'IE' => '/MSIE ([\d\.]+);|Trident\/7.0;.*rv:([\d\.]+)/',
        ];

        foreach ($browsers as $name => $pattern) {
            if (preg_match($pattern, $userAgent, $matches)) {
                $version = $matches[1] ?? $matches[2] ?? '';
                return ['name' => $name, 'version' => $version];
            }
        }

        return ['name' => '未知', 'version' => ''];
    }
}
